<?php

namespace App\Http\Controllers\Api;

use App\Models\Group;
use App\Models\OcrBlood;
use App\Models\OcrThen;
use App\Models\OcrUrine;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Http\Controllers\Controller;
use App\Models\Ocr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class OcrController extends Controller {

    // 列表
    public function lists(Request $request)
    {
        $user_id = auth('api')->id();
        $page = $request->post('page', 1);
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $model = Ocr::whereUserId($user_id);
        // 排序方式
        $sort_type = $request->post('sort_type') ?? 'time';
        if ($sort_type == 'group') {
            $model->orderBy('group_id', 'DESC');
        } elseif ($sort_type == 'project') {
            $model->orderBy('pro_name', 'ASC');
        } elseif ($sort_type == 'time') {
            $model->orderBy('id', 'DESC');
        }

        // 关键词搜索
        if ($keyword = $request->post('keyword')) {
            $model->where(function ($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                    ->orWhere('check_jg', 'like', "%{$keyword}%")
                    ->orWhere('pro_name', 'like', "%{$keyword}%");
            });
        }

        $list = $model->offset($offset)
            ->limit($limit)
            ->get([
                'id', 'img', 'check_jg', 'pro_name', 'created_at'
            ]);
        foreach ($list as $item) {
            $item->img = trim(config('app.url'), '/') . $item->img;
            if (is_object($item->created_at)) {
                $item->createdAt = $item->created_at->format('Y-m-d');
            } else {
                $item->createdAt = substr($item->created_at, 0, 8);
            }

        }
        return $this->writeJson(0, $list);
    }

    /**
     * 上传图片到分析方分析
     *
     * @param Request $request
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function upload(Request $request)
    {
        try {
            $ocr_path = $request->post('ocr_path');
            $ocr_path = str_replace(config('app.url'), '', $ocr_path);
            // 重复识别判断
            $model = Ocr::where('img_md5', md5(file_get_contents(public_path($ocr_path))))
                ->first();
            if ($model) {
                return $this->writeJson(0,[
                    'id' => $model->id
                ],'分析成功');
            }

            $client = new Client([
                'timeout'  => 60,
            ]);
            $res = $client->post('http://49.4.5.18:8088/zgocrimage/ocr/image', [
                'multipart' => [
                    [
                        'name' => 'myfile',
                        'contents' => fopen(public_path($ocr_path), 'r')
                    ]
                ]
            ])->getBody()->getContents();
            $res = json_decode($res, true);
            \Log::info($res);

            $user_id = auth('api')->id();
            $basic =  $res['basic'] ?? [];
            if ($basic && $res['item'] ?? []) {
                $basic = array_merge($basic, [
                    [
                        "name" => 'group_id',
                        "content" => ""
                    ],
                    [
                        "name" => 'user_id',
                        "content" => $user_id,
                    ]
                ]);
                $Ocr = new Ocr();
                if ($id = $Ocr->add($basic, $res['item'], '/'.$ocr_path)) {
                    return $this->writeJson(0,[
                        'id' => $id
                    ],'分析成功');
                }
            }
        } catch (\Exception $exception) {
            \Log::error($exception);
        }

        return $this->writeJson(500, null,'分析失败');
    }

    /**
     * 化验单的所有信息
     *
     * @param Request $request
     * @return bool
     */
    public function info(Request $request)
    {
        $id = $request->post('id');
        $user_id = auth('api')->id();
        $data = Ocr::whereUserId($user_id)
            ->where('id', $id)
            ->first();
        if (empty($data)) return $this->writeJson(500, null,'数据不存在');
        $data->group_name = Group::whereId($data->group_id)->value('name');
        $data->img = trim(config('app.url'), '/') . $data->img;

        if ($data->pro_name == '血常规') {
            $item = OcrBlood::whereOcrId($id)->first();
        } elseif ($data->pro_name == '便常规') {
            $item = OcrThen::whereOcrId($id)->first();
        } elseif ($data->pro_name == '尿常规') {
            $item = OcrUrine::whereOcrId($id)->first();
        }

        return $this->writeJson(0, [
            'basic' => $data,
            'item' => $item ?? []
        ],'获取成功');
    }

    /**
     * 编辑基础信息
     *
     * @param Request $request
     * @return bool
     */
    public function editBasic(Request $request)
    {
        $model = Ocr::whereUserId(auth('api')->id())
            ->where('id', $request->post('id'))
            ->first();
        if (empty($model)) return $this->writeJson(500, null,'数据不存在');
        $model->group_id = $request->post('group_id');
        $model->name = $request->post('name');
        $model->sex_name = $request->post('sex_name');
        $model->age = $request->post('age');
        if ($model->save()) {
            return $this->writeJson(0, null,'保存成功');
        } else {
            return $this->writeJson(500, null,'保存失败');
        }
    }

    // 编辑扩展信息
    public function editExt(Request $request)
    {
        /**
         * @var $id 扩展表id
         */
        $id = $request->post('id');
        $user_id = auth('api')->id();
        $pro_name = $request->post('pro_name');
        if ($pro_name == '血常规') {
            $result = (new OcrBlood())->edit($id, $user_id, $request->post());
        } elseif ($pro_name == '便常规') {
            $result = (new OcrThen())->edit($id, $user_id, $request->post());
        } elseif ($pro_name == '尿常规') {
            $result = (new OcrUrine())->edit($id, $user_id, $request->post());
        }

        if ($result ?? false) {
            return $this->writeJson(0, null,'保存成功');
        } else {
            return $this->writeJson(500, null,'保存失败');
        }
    }

    // 删除数据
    public function del(Request $request)
    {
        $id = $request->post('id');
        $user_id = auth('api')->id();

        $model = Ocr::whereUserId($user_id)
            ->where('id', $id)
            ->first();
        if (empty($model)) return $this->writeJson(500, null,'数据不存在');

        try {
            DB::beginTransaction();

            $pro_name = $model->pro_name;
            if ($pro_name == '血常规') {
                OcrBlood::whereOcrId($id)
                    ->where('user_id', $user_id)
                    ->delete();
            } elseif ($pro_name == '便常规') {
                OcrThen::whereOcrId($id)
                    ->where('user_id', $user_id)
                    ->delete();
            } elseif ($pro_name == '尿常规') {
                OcrUrine::whereOcrId($id)
                    ->where('user_id', $user_id)
                    ->delete();
            }
            $model->delete();

            DB::commit();
            return $this->writeJson(0, null,'删除成功');
        } catch (\Exception $exception) {
            DB::rollBack();
        }
        return $this->writeJson(500, null,'删除失败');
    }
}
